﻿
using JNPF.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PARK.Accessctl.Entitys;
using PARK.Attend.Entitys;
using PARK.BussinCache.Entitys.Entity;
using PARK.BussinCache.Interfaces;
using PARK.CardAcct.Entitys;
using PARK.Consumer;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.TaskScheduler.Interfaces;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PARK.TaskScheduler
{
    /// <summary>
    /// 宇泛设备事件队列
    /// </summary>
    [ApiDescriptionSettings(Tag = "UniEvtJob", Name = "uniEvtJobtask", Order = 220)]
    [Route("api/[controller]")]
    public class UniEvtJobService : BackgroundService, IUniEvtJobService, IDynamicApiController, ITransient
    {
        private readonly SqlSugarScope _db;
        private readonly int _times = 0;
        private readonly IConsumRefundRepository _ConsumRefundRepository;
        private readonly IParkCacheRepository _parkCacheRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="db"></param>
        /// <param name="consumRefundRepository"></param>
        public UniEvtJobService(ILogger<RefundJobService> logger,
            ISqlSugarClient db,
            IConsumRefundRepository consumRefundRepository,
            IParkCacheRepository parkCacheRepository)
        {
            _db = (SqlSugarScope)db;
            _ConsumRefundRepository = consumRefundRepository;
            _parkCacheRepository = parkCacheRepository;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

        }
        /// <summary>
        /// 启动自启动任务
        /// </summary>
        [NonAction]
        public async void StartTimerJob()
        {
            new LoggEx().Info("宇泛设备事件->队列开始执行...");
            CancellationToken stoppingToken = new CancellationToken();
            while (!stoppingToken.IsCancellationRequested)
            {
                await new TaskFactory().StartNew(() =>
                {
                    try
                    {
                        RunUniEvtQueue();
                    }
                    catch (Exception e)
                    {
                        new LoggEx().Info("宇泛设备事件,队列异常:=============失败=====" + e.Message);
                    }
                    //定时任务休眠
                    Thread.Sleep(500);
                });
            }
        }

        #region 解析处理人脸识别事件
        /// <summary>
        /// 解析处理人脸识别事件
        /// </summary>
        void RunUniEvtQueue()
        {
            try
            {
                var _Evt101004Json = _parkCacheRepository.GetEvt101004queueList();
                if (!string.IsNullOrEmpty(_Evt101004Json))
                {
                    var _Evt101004Entity= JsonConvert.DeserializeObject<UniEvt101004Entity>(_Evt101004Json);
                    if (_Evt101004Entity != null)
                    {
                        var Paras = new List<SugarParameter>();
                        var _AnyResult = 0;
                        var _AnyMsg = "";
                        //插入门禁记录
                        //获取对应人员
                        var _Employee = _db.Queryable<EmployeeEntity>().First(p => p.uni_admitGuid == _Evt101004Entity.admitGuid);
                        if (_Employee != null)
                        {
                            var _AccessEntity = new AccessRecordEntity();
                            _AccessEntity.Create();
                            _AccessEntity.EmployeeId = _Employee.EmployeeId;
                            _AccessEntity.JobNo = _Employee.JobNum;
                            _AccessEntity.ReallName = _Employee.RealName;
                            _AccessEntity.CardNo = _Employee.CardNo;
                            _AccessEntity.CatCardNo = _Employee.CatCardNo;
                            _AccessEntity.CompanyId = _Employee.CompanyId;
                            _AccessEntity.CompanyName = _Employee.CompanyName;
                            _AccessEntity.DepartId = _Employee.DepartId;
                            _AccessEntity.DepartName = _Employee.DepartName;
                            //门禁信息
                            _AccessEntity.CtlId = _Evt101004Entity.CtlId;
                            _AccessEntity.CtlSn = _Evt101004Entity.deviceNo;
                            _AccessEntity.ctlName = _Evt101004Entity.deviceName;
                            _AccessEntity.CtlInex = _Evt101004Entity.eventGuid;
                            _AccessEntity.Ctlposition = _Evt101004Entity.Ctlposition;                            
                            _AccessEntity.DoorAreaId = _Evt101004Entity.DoorAreaId;
                            _AccessEntity.DoorAreaName = _Evt101004Entity.DoorAreaName;
                            _AccessEntity.IsAtt = _Evt101004Entity.IsAtt;
                            _AccessEntity.InOrout = 1;
                            _AccessEntity.InOroutName = "出";                            
                            _AccessEntity.IsToAtt = 0;                            
                            _AccessEntity.PassStatus = 1;
                            _AccessEntity.PassStatusName = "通过";
                            _AccessEntity.Passtime = _Evt101004Entity.showTimeDate; //开门时间
                            //入库
                            _db.Insertable(_AccessEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommand();                           
                            //if (_AccessEntity.IsAtt == 1)
                            //{
                            //    //插入考勤记录
                            //    AttendRecordEntity attendRecord = new AttendRecordEntity();
                            //    attendRecord.Create();
                            //    attendRecord.accessreId = _AccessEntity.Id;
                            //    attendRecord.EmployeeId = _Employee.EmployeeId;
                            //    attendRecord.JobNo = _Employee.JobNum;
                            //    attendRecord.CardNo = _Employee.CardNo;
                            //    attendRecord.ReallName = _Employee.RealName;
                            //    attendRecord.DepartId = _Employee.DepartId;
                            //    attendRecord.DepartName = _Employee.DepartName;
                            //    attendRecord.worktype = 1;
                            //    attendRecord.SignType = 1;
                            //    attendRecord.SignTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            //    attendRecord.SignStatus = 1;
                            //    attendRecord.SignMint = 0;
                            //    attendRecord.ctlId = _Evt101004Entity.CtlId;
                            //    attendRecord.ctlSn = _Evt101004Entity.deviceNo;
                            //    attendRecord.ctlName = _Evt101004Entity.deviceName;
                            //    attendRecord.CompanyId = _Employee.CompanyId;
                            //    attendRecord.CompanyName = _Employee.CompanyName;
                            //    //入库
                            //    _db.Insertable(attendRecord).IgnoreColumns(ignoreNullColumn: true).ExecuteCommand();
                            //}
                        }
                        //更新解析状态
                        StringBuilder _upSql = new StringBuilder("update access_uni_Evt101004 set ");
                        _upSql.AppendFormat(" IsAny={0},", 1);
                        _upSql.AppendFormat(" Anydate='{0}',", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        _upSql.AppendFormat(" AnyResult={0},", _AnyResult);
                        _upSql.AppendFormat(" AnyMsg='{0}'", _AnyMsg);
                        _upSql.AppendFormat(" where RdsId='{0}'", _Evt101004Entity.RdsId);
                        _db.Ado.ExecuteCommand(_upSql.ToString(), Paras);
                    }
                }
            }
            catch(Exception ex)
            {
                new LoggEx().errlog("解析处理人脸识别事件,异常:" + ex.Message);
            }
        }
        #endregion
    }
}
